package com.nondo.rdp.finance.service.impl;

import com.nondo.rdp.auth.domain.Role;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.finance.domain.Activity;
import com.nondo.rdp.finance.repository.ActivityRepository;
import com.nondo.rdp.finance.service.ActivityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    ActivityRepository activityRepository;

    @Override
    public Activity findOne(Long id) {
        return this.activityRepository.findOne(id);
    }

    @Override
    public Activity save(Activity activity) {
        return this.activityRepository.save(activity);
    }

    @Override
    public void update(Activity activity) {
        this.activityRepository.save(activity);
    }

    @Override
    public void delete(Long id) {
        this.activityRepository.deleteById(id);
    }

    @Override
    public Page<Activity> findAll(Page<Activity> page, Activity activity) {
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Activity> dictPage = activityRepository.findAll((root, query, builder) -> {

            List<Predicate> predicates = new ArrayList<>();
            //搜索标题
            if (StringUtils.isNotEmpty(activity.getTitle())) {
                predicates.add(builder.like(root.get("title"), "%" + activity.getTitle() + "%"));
            }
            //搜索ID
            if (activity.getId() != null && activity.getId() != 0) {
                predicates.add(builder.equal(root.get("id"), activity.getId()));
            }
            predicates.add(builder.like(root.get("delFlag"), Role.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);
            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<Activity>(dictPage);
    }
}